import User.User;
import User.Duser;
import User.people;

import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "dgut_login")
public class dgut_login extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
        doDgut_login(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
        doDgut_login(request, response);
    }
    protected void doDgut_login(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
    {
        people p = (people)request.getSession().getAttribute("LOGIN");
        Duser duser = null;
        if(p != null)
        {
            String id = p.getUsername();
            String name = p.getName();
            String passwd = "123456";
            if(Treatment.isRight_dgut(id))//判断这个莞工id是否已经在本地注册或者绑定过
            {
                EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyDSTest");
                EntityManager entityManager = entityManagerFactory.createEntityManager();
                duser = entityManager.find(Duser.class, duser.getId());
                Query query = entityManager.createNativeQuery("SELECT * FROM USER", User.class);
                List<User> list = query.getResultList();
                if(list != null)
                {
                    Iterator<User> iterator = list.iterator();
                    while(iterator.hasNext())
                    {
                        User user = iterator.next();
                        if(user.getDgutid().equals(duser.getId()))
                        {
                            request.getSession().setAttribute("SELF", user);
                            request.getSession().setAttribute("DGUT", duser);
                            response.sendRedirect("/user.jsp");
                        }
                    }
                }
            }
            else //为这个莞工账户创一个本地账号
            {
                duser = new Duser(id, name, null, passwd, "userimags/0.jpg");
                request.getSession().setAttribute("DGUT", duser);
                response.sendRedirect("/addEmail.jsp");
            }
        }
    }
}
